import React, { useState, useEffect } from 'react';
import { Card, DatePicker, Select, Row, Col, Statistic, Table, Typography } from 'antd';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell } from 'recharts';
import { SearchOutlined, CalendarOutlined, UserOutlined, ScheduleOutlined, FileTextOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Title } = Typography;

// 类型定义
interface StatisticsData {
  date: string;
  newMembers: number;
  loginMembers: number;
  appointmentMembers: number;
  reportUploads: number;
}

interface SummaryStats {
  totalNewMembers: number;
  totalLoginMembers: number;
  totalAppointments: number;
  totalReports: number;
  growthRate: number;
}

interface PieChartDataItem {
  name: string;
  value: number;
  color: string;
}

// 修复：为 Pie 标签添加类型定义
interface PieLabelProps {
  name: string;
  percent: number;
}

const MemberStatistics: React.FC = () => {
  // 状态管理
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(1, 'day'),
    dayjs()
  ]);
  const [statisticsType, setStatisticsType] = useState<string>('newMembers');
  const [statisticsData, setStatisticsData] = useState<StatisticsData[]>([]);
  const [summaryStats, setSummaryStats] = useState<SummaryStats>({
    totalNewMembers: 0,
    totalLoginMembers: 0,
    totalAppointments: 0,
    totalReports: 0,
    growthRate: 0
  });
  const [loading, setLoading] = useState<boolean>(false);

  // 统计类型选项
  const statisticsTypes = [
    { value: 'newMembers', label: '新增会员', color: '#1890ff', icon: <UserOutlined /> },
    { value: 'loginMembers', label: '今日登录会员', color: '#52c41a', icon: <UserOutlined /> },
    { value: 'appointmentMembers', label: '预约人数', color: '#faad14', icon: <ScheduleOutlined /> },
    { value: 'reportUploads', label: '报告上传', color: '#f5222d', icon: <FileTextOutlined /> }
  ];

  // 模拟数据获取
  const fetchStatisticsData = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 生成模拟数据
      const mockData: StatisticsData[] = [];
      const startDate = dateRange[0];
      const endDate = dateRange[1];
      const daysDiff = endDate.diff(startDate, 'day');
      
      for (let i = 0; i <= daysDiff; i++) {
        const currentDate = startDate.add(i, 'day');
        mockData.push({
          date: currentDate.format('YYYY-MM-DD'),
          newMembers: 1,
          loginMembers: 1,
          appointmentMembers: 3,
          reportUploads: 1
        });
      }
      
      setStatisticsData(mockData);
      
      // 计算汇总统计
      const totals = mockData.reduce((acc, curr) => ({
        totalNewMembers: acc.totalNewMembers + curr.newMembers,
        totalLoginMembers: acc.totalLoginMembers + curr.loginMembers,
        totalAppointments: acc.totalAppointments + curr.appointmentMembers,
        totalReports: acc.totalReports + curr.reportUploads,
        growthRate: 0
      }), {
        totalNewMembers: 0,
        totalLoginMembers: 0,
        totalAppointments: 0,
        totalReports: 0,
        growthRate: 0
      });
      
      setSummaryStats({
        ...totals,
        growthRate: 12.5 // 模拟增长率
      });
    } catch (error) {
      console.error('获取统计数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 初始化数据和监听日期/类型变化
  useEffect(() => {
    fetchStatisticsData();
  }, [dateRange, statisticsType]);

  // 处理日期范围变化
  const handleDateRangeChange = (dates: any) => {
    if (dates && dates.length === 2) {
      setDateRange([dates[0], dates[1]]);
    }
  };

  // 处理统计类型变化
  const handleStatisticsTypeChange = (value: string) => {
    setStatisticsType(value);
  };

  // 获取当前选中的统计类型配置
  const getCurrentStatType = () => {
    return statisticsTypes.find(type => type.value === statisticsType) || statisticsTypes[0];
  };

  // 准备图表数据
  const chartData = statisticsData.map(item => ({
    date: item.date,
    value: item[statisticsType as keyof StatisticsData] as number
  }));

  // 修复：直接定义饼图数据，避免复杂的动态属性访问
  const pieChartData: PieChartDataItem[] = [
    {
      name: '新增会员',
      value: summaryStats.totalNewMembers,
      color: '#1890ff'
    },
    {
      name: '登录会员',
      value: summaryStats.totalLoginMembers,
      color: '#52c41a'
    },
    {
      name: '预约人数',
      value: summaryStats.totalAppointments,
      color: '#faad14'
    },
    {
      name: '报告上传',
      value: summaryStats.totalReports,
      color: '#f5222d'
    }
  ];

  // 修复：为饼图标签添加类型安全的渲染函数
  const renderPieLabel = (props: PieLabelProps) => {
    const { name, percent } = props;
    return `${name}: ${(percent * 100).toFixed(0)}%`;
  };

  // 表格列定义
  const columns = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      width: 120,
    },
    {
      title: '新增会员',
      dataIndex: 'newMembers',
      key: 'newMembers',
      width: 100,
      render: (value: number) => <span style={{ color: '#1890ff' }}>{value}</span>
    },
    {
      title: '登录会员',
      dataIndex: 'loginMembers',
      key: 'loginMembers',
      width: 100,
      render: (value: number) => <span style={{ color: '#52c41a' }}>{value}</span>
    },
    {
      title: '预约人数',
      dataIndex: 'appointmentMembers',
      key: 'appointmentMembers',
      width: 100,
      render: (value: number) => <span style={{ color: '#faad14' }}>{value}</span>
    },
    {
      title: '报告上传',
      dataIndex: 'reportUploads',
      key: 'reportUploads',
      width: 100,
      render: (value: number) => <span style={{ color: '#f5222d' }}>{value}</span>
    }
  ];

  const currentType = getCurrentStatType();

  return (
    <div style={{ padding: '24px', background: '#f0f2f5', minHeight: '100vh' }}>
      {/* 页面标题和面包屑 */}
      <div style={{ marginBottom: '24px' }}>
        <div style={{ fontSize: '20px', fontWeight: 'bold', marginBottom: '8px' }}>
          会员统计
        </div>
        <div style={{ color: '#999', fontSize: '14px' }}>
          会员管理 / 会员统计
        </div>
      </div>

      {/* 筛选条件卡片 */}
      <Card style={{ marginBottom: '24px' }}>
        <Row gutter={16} align="middle">
          <Col span={8}>
            <div style={{ marginBottom: '8px', fontWeight: '500' }}>日期范围</div>
            <RangePicker
              value={dateRange}
              onChange={handleDateRangeChange}
              style={{ width: '100%' }}
              allowClear={false}
            />
          </Col>
          <Col span={8}>
            <div style={{ marginBottom: '8px', fontWeight: '500' }}>统计类型</div>
            <Select
              value={statisticsType}
              onChange={handleStatisticsTypeChange}
              style={{ width: '100%' }}
              suffixIcon={<SearchOutlined />}
            >
              {statisticsTypes.map(type => (
                <Option key={type.value} value={type.value}>
                  <span style={{ color: type.color }}>
                    {type.icon} {type.label}
                  </span>
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={8}>
            <div style={{ marginBottom: '8px', fontWeight: '500' }}>统计周期</div>
            <Select defaultValue="daily" style={{ width: '100%' }}>
              <Option value="daily">日统计</Option>
              <Option value="weekly">周统计</Option>
              <Option value="monthly">月统计</Option>
            </Select>
          </Col>
        </Row>
      </Card>

      {/* 统计概览卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="新增会员"
              value={summaryStats.totalNewMembers}
              valueStyle={{ color: '#1890ff' }}
              prefix={<UserOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="登录会员"
              value={summaryStats.totalLoginMembers}
              valueStyle={{ color: '#52c41a' }}
              prefix={<UserOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="预约人数"
              value={summaryStats.totalAppointments}
              valueStyle={{ color: '#faad14' }}
              prefix={<ScheduleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="报告上传"
              value={summaryStats.totalReports}
              valueStyle={{ color: '#f5222d' }}
              prefix={<FileTextOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 主要图表区域 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={16}>
          <Card 
            title={
              <span>
                {currentType.icon} {currentType.label}趋势图
                <span style={{ fontSize: '14px', color: '#666', marginLeft: '8px' }}>
                  ({dateRange[0].format('YYYY-MM-DD')} 至 {dateRange[1].format('YYYY-MM-DD')})
                </span>
              </span>
            }
            loading={loading}
          >
            <ResponsiveContainer width="100%" height={400}>
              <LineChart data={chartData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="date" 
                  tickFormatter={(value: string) => dayjs(value).format('MM-DD')}
                />
                <YAxis />
                <Tooltip 
                  formatter={(value: number) => [`${value}`, currentType.label]}
                  labelFormatter={(label: string) => `日期: ${label}`}
                />
                <Legend />
                <Line 
                  type="monotone" 
                  dataKey="value" 
                  stroke={currentType.color}
                  strokeWidth={2}
                  name={currentType.label}
                  dot={{ fill: currentType.color }}
                />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        
        <Col span={8}>
          <Card title="数据分布概览" loading={loading}>
            <ResponsiveContainer width="100%" height={400}>
              <PieChart>
                <Pie
                  data={pieChartData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={renderPieLabel}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {pieChartData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip formatter={(value: number) => [value, '数量']} />
              </PieChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      {/* 对比分析 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={12}>
          <Card title="各类型数据对比" loading={loading}>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={statisticsData.slice(-7)}> {/* 最近7天数据 */}
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="date" 
                  tickFormatter={(value: string) => dayjs(value).format('MM-DD')}
                />
                <YAxis />
                <Tooltip />
                <Legend />
                <Bar dataKey="newMembers" name="新增会员" fill="#1890ff" />
                <Bar dataKey="loginMembers" name="登录会员" fill="#52c41a" />
                <Bar dataKey="appointmentMembers" name="预约人数" fill="#faad14" />
                <Bar dataKey="reportUploads" name="报告上传" fill="#f5222d" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        
        <Col span={12}>
          <Card title="增长率分析" loading={loading}>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={chartData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="date" 
                  tickFormatter={(value: string) => dayjs(value).format('MM-DD')}
                />
                <YAxis />
                <Tooltip />
                <Legend />
                {statisticsTypes.map(type => (
                  <Line 
                    key={type.value}
                    type="monotone" 
                    dataKey={type.value} 
                    stroke={type.color}
                    name={type.label}
                    strokeWidth={2}
                  />
                ))}
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      {/* 详细数据表格 */}
      <Card 
        title="详细数据"
        extra={
          <span style={{ color: '#666', fontSize: '14px' }}>
            共 {statisticsData.length} 条记录
          </span>
        }
        loading={loading}
      >
        <Table
          columns={columns}
          dataSource={statisticsData.map((item, index) => ({ ...item, key: index }))}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total: number, range: number[]) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
          }}
          scroll={{ x: 800 }}
        />
      </Card>
    </div>
  );
};

export default MemberStatistics;